<template>
  <el-dialog
    :title="title"
    width="700px"
    top="50px"
    append-to-body
    destroy-on-close
    :close-on-click-modal="false"
    :visible="dialogVisible"
    class="user-select-checkbox"
    @close="close"
  >
    <el-row v-if="dialogVisible" v-loading="wrapperLoading">
      <el-col :span="16">
        <el-card shadow="never" class="mr10 dialog-page-full left-wrapper">
          <div class="left-top">
            <el-row :gutter="10">
              <el-col :span="9">
                <el-input v-model="searchForm.organizeName" placeholder="部门名称关键词" />
              </el-col>
              <el-col :span="9">
                <el-input v-model="searchForm.userName" placeholder="人员名称关键词" />
              </el-col>
              <el-col :span="6">
                <el-button :loading="searchLoading" icon="el-icon-search" @click="doSearch"
                  >搜索</el-button
                >
              </el-col>
            </el-row>
          </div>

          <div v-loading="leftWrapperLoading" class="left-bottom" flex>
            <div class="left-left-wrapper">
              <el-scrollbar style="height: 100%">
                <div class="p10">
                  <el-tree
                    ref="tree"
                    node-key="id"
                    :data="treeData"
                    :highlight-current="true"
                    :props="{
                      children: 'childList',
                      label: 'name',
                      isLeaf: 'leaf',
                    }"
                    :load="loadNode"
                    lazy
                    @node-click="nodeClick"
                  />
                </div>
              </el-scrollbar>
            </div>

            <div class="left-right-wrapper">
              <el-scrollbar style="height: 100%">
                <div class="p10">
                  <div v-if="!personArr.length" class="empty-wrapper fcc">暂无数据</div>
                  <template v-else>
                    <el-checkbox
                      v-model="checkAll"
                      :indeterminate="isIndeterminate"
                      @change="handleCheckAllChange"
                      >全选</el-checkbox
                    >
                    <div v-for="(item, index) in personArr" :key="index" class="checkbox-wrapper">
                      <el-checkbox
                        v-model="item.checked"
                        :label="item.uid"
                        :disabled="selectedUserIdArr.includes(item.uid)"
                        @change="(val) => personChange({ item })"
                        >{{ item.userName }}</el-checkbox
                      >
                    </div>
                  </template>
                </div>
              </el-scrollbar>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="8">
        <el-card shadow="never" class="ml5 dialog-page-full">
          <div v-if="!checkedPersonArr.length" class="empty-wrapper fcc">暂无数据</div>

          <el-scrollbar v-else style="height: 100%">
            <div class="right-wrapper">
              <draggable
                :list="checkedPersonArr"
                class="list-group"
                ghost-class="ghost"
                :disabled="!draggableFlag"
              >
                <div
                  v-for="(item, index) in checkedPersonArr"
                  :key="index"
                  class="right-item fbc"
                  :class="{ pointer: draggableFlag }"
                >
                  <span class="username">{{ item.userName }}</span>
                  <el-button type="text" class="danger" @click="doDel({ index, item })"
                    >删除</el-button
                  >
                </div>
              </draggable>
            </div>
          </el-scrollbar>
        </el-card>
      </el-col>
    </el-row>

    <span slot="footer">
      <el-button :loading="btnLoading" type="primary" @click="submitData">确定</el-button>
      <el-button @click="close">取消</el-button>
    </span>
  </el-dialog>
</template>

<script>
import dialogMixin from "mixins/dialogMixin";
import organizeSimpleTreeMixins from "mixins/organizeSimpleTreeMixins";
import { OrganizeSimpleAllTree, UserSimpleList } from "api/sys/organize";
import { cloneDeep } from "lodash";
import draggable from "vuedraggable";

export default {
  components: { draggable },
  mixins: [dialogMixin, organizeSimpleTreeMixins],
  props: {
    // 当前行数据
    currentRowObj: {
      type: Object,
      default: () => ({}),
    },
    /**
     * 父组件传递过来的已选中的人员
     */
    currentCheckedArr: {
      type: Array,
      default: () => [],
    },
    /**
     * 主动获取已选中的人员
     */
    loadCheckedArr: {
      type: Function,
      default: null,
    },
    idKey: {
      type: String,
      default: "roleId",
    },
    title: {
      type: String,
      default: "人员选择",
    },
    // 已选中人员，用于过滤这批数据不能被选中
    selectedUserIdArr: {
      type: Array,
      default: () => [],
    },
    // 选中数据是否能拖拽
    draggableFlag: {
      type: Boolean,
      default: false,
    },
    parentId: {
      type: Number,
      default: 0,
    },
    // 树查询参数
    treeParams: {
      type: Object,
      default: () => null,
    },
  },
  data() {
    return {
      // 顶部搜索对象
      searchForm: {
        // 机构名
        organizeName: "",
        // 用户名
        userName: "",
      },
      // 搜索按钮的loading
      searchLoading: false,
      // 左侧面板的loading
      leftWrapperLoading: false,
      // 人员列表
      personArr: [],
      // 已选择人员列表
      checkedPersonArr: [],
      treeData: [],
      // 全选
      checkAll: false,
    };
  },
  computed: {
    isIndeterminate() {
      const { length } = this.personArr.filter((item) => item.checked);
      return length > 0 && length < this.personArr.length;
    },
  },
  watch: {
    personArr: {
      deep: true,
      handler(val) {
        const { length } = val.filter((item) => item.checked);
        this.checkAll = length === val.length;
      },
    },
  },
  methods: {
    /**
     * 获取角色关联人员列表
     */
    async initForm() {
      if (this.loadCheckedArr) {
        try {
          this.wrapperLoading = true;
          const data = await this.loadCheckedArr(this.currentRowObj[this.idKey]);
          this.checkedPersonArr = data;
        } catch (e) {
          console.log(e);
        } finally {
          this.wrapperLoading = false;
        }
      } else {
        this.checkedPersonArr = cloneDeep(this.currentCheckedArr);
      }
    },
    /**
     * 树节点的点击事件
     */
    async nodeClick(data) {
      const { id } = data;
      try {
        const data = await UserSimpleList(id);
        this.setPersonArr(data);
      } catch (e) {
        console.log(e);
      }
    },
    /**
     * 设置部门下的人员列表
     */
    setPersonArr(data) {
      const tempArr = this.checkedPersonArr.map((item) => item.uid);
      data.map((item) => {
        if (!tempArr.length) {
          item.checked = false;
        } else {
          item.checked = tempArr.includes(item.uid);
        }
      });
      this.personArr = data;
    },
    /**
     * 中间区域的选择事件
     */
    personChange({ item }) {
      const { checked, uid } = item;
      if (!this.checkedPersonArr.length) {
        if (checked) {
          this.checkedPersonArr.push(item);
        }
      } else {
        if (checked) {
          this.checkedPersonArr.push(item);
        } else {
          this.checkedPersonArr = this.checkedPersonArr.filter((item1) => item1.uid !== uid);
        }
      }
    },
    /**
     * 删除已经选择的角色
     */
    async doDel({ index, item }) {
      await this.$myConfirm("删除本条数据吗");
      this.checkedPersonArr.splice(index, 1);
      const { uid } = item;
      this.personArr.map((item) => {
        if (item.uid === uid) {
          item.checked = false;
        }
      });
    },
    /**
     * 提交数据
     */
    submitData() {
      this.$emit("success", this.checkedPersonArr);
      this.close();
    },
    /**
     * 搜索数据
     */
    async _OrganizeSimpleAllTree() {
      if (this.searchForm.organizeName || this.searchForm.userName) {
        try {
          this.searchLoading = true;
          this.leftWrapperLoading = true;
          const data = await OrganizeSimpleAllTree(this.$clearEmptyObjAttritube(this.searchForm));
          if (data) {
            const { organizeTree, userList } = data;
            this.treeData = organizeTree || [];
            if (userList) {
              this.personArr = userList;
              this.setPersonArr(userList);
            } else {
              this.personArr = [];
            }
          }
        } catch (e) {
          console.log(e);
        } finally {
          this.searchLoading = false;
          this.leftWrapperLoading = false;
        }
      } else {
        // 重新加载
        this.node_had.childNodes = [];
        this.loadNode(this.node_had, this.resolve_had);
        this.personArr = [];
      }
    },
    /**
     * 搜索
     */
    doSearch() {
      this._OrganizeSimpleAllTree();
    },
    /**
     * 全选、全取消
     */
    handleCheckAllChange(val) {
      if (val) {
        // 全选
        this.personArr.map((item) => (item.checked = true));
        let obj = this.getCheckedObj();
        // 增加新数据
        this.personArr.map((item) => {
          const { uid, userName } = item;
          obj[uid] = userName;
        });
        this.setCheckedPersonArr(obj);
      } else {
        // 全取消
        this.personArr.map((item) => (item.checked = false));
        let obj = this.getCheckedObj();
        // 删除取消的数据
        this.personArr.map((item) => {
          delete obj[item.uid];
        });
        this.setCheckedPersonArr(obj);
      }
    },
    /**
     * 获取选中的对象
     */
    getCheckedObj() {
      let obj = {};
      this.checkedPersonArr.map((item) => {
        const { uid, userName } = item;
        obj[uid] = userName;
      });
      return obj;
    },
    /**
     * 设置右侧选中的数据
     */
    setCheckedPersonArr(obj) {
      let arr = [];
      Object.keys(obj).map((item) => {
        arr.push({ uid: +item, userName: obj[item] });
      });
      this.checkedPersonArr = arr;
    },
  },
};
</script>

<style lang="scss" scoped>
.user-select-checkbox {
  ::v-deep .el-scrollbar {
    .el-scrollbar__wrap {
      overflow-x: hidden;
    }
  }
  .dialog-page-full {
    height: calc(100vh - 262px);
    position: relative;
    .empty-wrapper {
      height: 100%;
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
    }
  }
  ::v-deep .el-card__body {
    display: flex;
    flex-direction: column;
    height: 100%;
    padding: 0 !important;
    .left-top {
      border-bottom: 1px solid #ebeef5;
      padding: 10px;
    }
    .left-bottom {
      flex: 1;
      height: calc(100% - 53px);
      .left-left-wrapper {
        height: 100%;
        flex: 1;
        border-right: 1px solid #ebeef5;
      }
      .el-scrollbar {
        flex: 1;
      }
      .left-right-wrapper {
        height: 100%;
        flex: 1;
        flex-shrink: 0;
        .checkbox-wrapper {
          padding: 5px 0;
        }
      }
    }
  }

  .right-wrapper {
    padding: 0 10px 0 10px;
    .right-item:not(:last-child) {
      border-bottom: 1px solid #ebeef5;
    }
  }

  ::v-deep .el-checkbox__label {
    font-size: 12px !important;
    line-height: 18px !important;
  }
  ::v-deep .el-tree-node__label {
    font-size: 12px !important;
    line-height: 18px;
  }

  .username,
  .empty-wrapper {
    font-size: 12px;
    color: #606266;
  }
}
</style>
